package cn.dylan.system.service.impl;

import cn.dylan.basic.service.impl.BaseServiceImpl;
import cn.dylan.system.domain.Menu;
import cn.dylan.system.mapper.MenuMapper;
import cn.dylan.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> deptTree() {
        List<Menu> departments = menuMapper.loadAll();

        HashMap<Long, Menu> map = new HashMap<>();

        for (Menu Menu : departments) {
            map.put(Menu.getId(),Menu);
        }
        List<Menu> deptTree = new ArrayList<>();
        for (Menu Menu : departments) {
            if(Menu.getParent_id()==null){
                deptTree.add(Menu);
            }else{
                // 根据parent_id 获取上级部门对象
                Long parent_id = Menu.getParent_id();
                Menu parentDepartment = map.get(parent_id);
                // 把当前非顶级部门对象放入其上级部门对应的子集部门中
                parentDepartment.getChildren().add(Menu);
            }
        }
        return deptTree;
    }
}
